<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始时间" />
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
        <el-popover v-model:visible="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteSelectedRow">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>

      <el-table
        ref="multipleTable"
        style="width: 100%"
        border
        :header-cell-style="{background:'#a3c6d2',color:'#849ba1'}"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="日期" :show-overflow-tooltip="true">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="left" label="IP" prop="ftpIp" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="端口" prop="ftpPort" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="用户名" prop="ftpUser" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="文件名" prop="ftpFileName" :show-overflow-tooltip="true" />

        <el-table-column align="left" label="存储服务器" prop="storeServer" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="存储路径" prop="storePath" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="存储文件夹" prop="storeFolder" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="存储文件名" prop="storeFileName" :show-overflow-tooltip="true" />

        <el-table-column align="left" label="解析模式" prop="jsonDb" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="ods库名" prop="odsDbName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="ods表名" prop="odsTbName" :show-overflow-tooltip="true" />

        <el-table-column align="left" label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="updateOdsFtpFunc(scope.row)">变 更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="ftp配置" class="dialog-mid">
      <el-form ref="elFormRef" :model="formData" label-position="right" :rules="rule" class="x-form" :inline="true" style="border: 0px">
        <div style="border: 1px solid #538ea4;margin-top: 10px">
          <span class="div_span" style="width: 75px;">ftp 服务器</span>
          <el-form-item label="Ip:" prop="ftpIp">
            <el-input v-model="formData.ftpIp" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="端口号:" prop="ftpPort">
            <el-input v-model="formData.ftpPort" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="用户名:" prop="ftpUser">
            <el-input v-model="formData.ftpUser" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="密码:" prop="ftpPwd">
            <el-input v-model="formData.ftpPwd" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="连接超时(秒):" prop="ftpTimeOut">
            <el-input v-model="formData.ftpTimeOut" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="指定路径:" prop="ftpPath">
            <el-input v-model="formData.ftpPath" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="限定文件夹:" prop="ftpFolder">
            <el-input v-model="formData.ftpFolder" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="限定文件名:" prop="ftpFileName">
            <el-input v-model="formData.ftpFileName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="限定文件后缀:" prop="ftpFileType">
            <el-input v-model="formData.ftpFileType" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="限定文件时限:" prop="ftpFileLimitTime">
            <el-input v-model="formData.ftpFileLimitTime" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="下载后删除:" prop="ftpDelAfterDownload">
            <el-switch v-model="formData.ftpDelAfterDownload" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" clearable />
          </el-form-item>
        </div>
        <div style="border: 1px solid #538ea4;margin-top: 10px">
          <span class="div_span" style="width: 90px;">存储服务器</span>
          <el-form-item label="存储服务器:" prop="storeServer">
            <el-select v-model="formData.storeServer">
              <el-option v-for="item in ftpStoreServerType" :key="item.id" :value="item.label" :label="item.label" />
            </el-select>
          </el-form-item>
          <template v-if="formData.storeServer !== '本地服务器'">
            <el-form-item label="Ip:" prop="storeIp">
              <el-input v-model="formData.storeIp" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="端口号:" prop="storePort">
              <el-input v-model="formData.storePort" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="用户名:" prop="storeUser">
              <el-input v-model="formData.storeUser" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="密码:" prop="storePwd">
              <el-input v-model="formData.storePwd" placeholder="请输入" />
            </el-form-item>
          </template>
          <el-form-item label="文件存储路径:" prop="storePath">
            <el-input v-model="formData.storePath" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="存储文件夹:" prop="storeFolder">
            <el-input v-model="formData.storeFolder" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="存储文件名:" prop="storeFileName">
            <el-input v-model="formData.storeFileName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="存储文件后缀:" prop="storeFileType">
            <el-input v-model="formData.storeFileType" placeholder="请输入" />
          </el-form-item>
        </div>
        <div style="border: 1px solid #538ea4;margin-top: 10px">
          <span class="div_span" style="width: 100px;">数据解析入库</span>
          <el-form-item label="ftp文件类型:" prop="jsonDb">
            <el-select v-model="formData.jsonDb">
              <el-option v-for="item in ftpParseType" :key="item.id" :value="item.label" :label="item.label" />
            </el-select>
          </el-form-item>
          <template v-if="formData.jsonDb !== '不解析'">
            <el-form-item label="ods库名:" prop="odsDbName">
              <el-input v-model="formData.odsDbName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="ods表名:" prop="odsTbName">
              <el-input v-model="formData.odsTbName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="编码类型:" prop="charSet">
              <el-input v-model="formData.charSet" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="内容分割符:" prop="jsonSeparate">
              <el-input v-model="formData.jsonSeparate" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="字段映射:" prop="jsonMap">
              <el-select v-model="formData.jsonMap" style="width:600px">
                <el-option v-for="item in ftpParseType" :key="item.id" :value="item.label" :label="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="主键名:" prop="ftpJsonKey">
              <el-input v-model="formData.ftpJsonKey" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="更新列名:" prop="updateCol">
              <el-input v-model="formData.updateCol" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="不清除列表:" prop="noCleanList">
              <el-input v-model="formData.noCleanList" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="数据不同处理方式:" prop="diffProc">
              <el-input v-model="formData.diffProc" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="新增处理方式:" prop="newProc">
              <el-input v-model="formData.newProc" placeholder="请输入" />
            </el-form-item>
          </template>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="warning" style="float: left;" @click="testFtp">ftp测试</el-button>
          <el-button v-if="ftpReport !== ''" type="warning" style="float: left;" @click="showReport">ftp测试报告</el-button>
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogReportVisible" :before-close="closeReport" title="ftp测试报告" class="dialog-small">
      <div style="border: 1px solid #538ea4;margin-top: 10px">
        <span style="white-space: pre-wrap;">{{ ftpReport }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OdsFtp'
}
</script>

<script setup>
import {
  createOdsFtp,
  deleteOdsFtp,
  deleteOdsFtpByIds,
  updateOdsFtp,
  findOdsFtp,
  getOdsFtpList,
  testOdsFtp,
  initOdsFtp,
} from '@/api/odsFtp'

import {
  formatDate,
} from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { getDict } from '@/utils/dictionary'

const formData = ref({
  ftpIp: '',
  ftpPort: '',
  ftpUser: '',
  ftp_pwd: '',
  ftpTimeOut: '',
  ftpPath: '',
  ftpFolder: '',
  ftpFileName: '',
  ftpFileType: '',
  ftpFileLimitTime: '',
  ftpDelAfterDownload: true,

  storeServer: '',
  storeIp: '',
  storePort: '',
  storeUser: '',
  storePwd: '',
  storeFolder: '',

  jsonDb: 0,
  jsonSeparate: '',
  jsonKey: '',
  jsonMap: '',
  odsDbName: '',
  odsTbName: '',
  charSet: '',
  updateCol: '',
  noCleanList: '',
  diffProc: '',
  newProc: '',
})
const ftpReport = ref('')
const rule = reactive({})

const elFormRef = ref()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const table = await getOdsFtpList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()


const setOptions = async() => {
}

setOptions()

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOdsFtpFunc(row)
  })
}

const deleteVisible = ref(false)

const deleteSelectedRow = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
  multipleSelection.value.map(item => {
    ids.push(item.ID)
  })
  const res = await deleteOdsFtpByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    await getTableData()
  }
}

const type = ref('')

const updateOdsFtpFunc = async(row) => {
  const res = await findOdsFtp({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.reodsFtp
    dialogFormVisible.value = true
  }
}

const deleteOdsFtpFunc = async(row) => {
  const res = await deleteOdsFtp({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    await getTableData()
  }
}

const dialogFormVisible = ref(false)
const dialogReportVisible = ref(false)
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}
const showReport = () => {
  dialogReportVisible.value = true
}
const closeReport = () => {
  dialogReportVisible.value = false
}
const closeDialog = () => {
  dialogFormVisible.value = false
  ftpReport.value = ''
  formData.value = {
    jsonDb: 0,
  }
}
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createOdsFtp(formData.value)
        break
      case 'update':
        res = await updateOdsFtp(formData.value)
        break
      default:
        res = await createOdsFtp(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      await getTableData()
    }
  })
}
const testFtp = async() => {
  const res = await testOdsFtp(formData.value)
  ftpReport.value = res.msg
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '测试ftp成功'
    })
  }
}

const initData = ref([])

const initFtp = async() => {
  const res = await initOdsFtp()
  if (res.code === 0) {
    initData.value = res.data.odsFtpCmts
  }
}

const ftpStoreServerType = ref([])
const ftpParseType = ref([])
const initDict = async() => {
  ftpStoreServerType.value = await getDict('ftpStoreServer')
  ftpParseType.value = await getDict('ftpParseType')
}
const init = async() => {
  await initDict()
  await initFtp()
}
onMounted(async() => {
  await init()
})

</script>

<style>
</style>
